﻿using Ndns.Packet.Abstractions;
using System.Buffers;
using System.Collections.Generic;
using System.IO;

namespace Ndns.Packet.Parser
{
    class DnsQueryParser
    {
        private readonly DnsHostNameParser _hostNameParser;
        private readonly ArrayPool<byte> _arrayPool;

        public DnsQueryParser(DnsHostNameParser hostNameParser) : this(hostNameParser, null) { }
        public DnsQueryParser(DnsHostNameParser hostNameParser, ArrayPool<byte> arrayPool)
        {
            _hostNameParser = hostNameParser;
            _arrayPool = arrayPool;
        }

        public bool TryParse(Stream stream, IDictionary<DnsHostNamePointer, DnsHostName> symbols, ref int offset, out DnsQuery query)
        {
            if (!_hostNameParser.TryParse(stream, symbols, ref offset, out var hostName))
            {
                query = null;
                return false;
            }
            
            var vType = stream.ReadNetworkUInt16();
            var vClass = stream.ReadNetworkUInt16();
            if (!PacketEndOfStreamException.CheckValue(vType) || !PacketEndOfStreamException.CheckValue(vClass))
            {
                query = null;
                return false;
            }
            offset += 4;

            query = new DnsQuery
            {
                HostName = hostName,
                Type = (DnsRecordType)vType,
                Class = (DnsClass)vClass
            };
            return true;
        }
    }
}
